package cn.samir.sudoku.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AbsListView.LayoutParams;
import cn.samir.sudoku.R;
import cn.samir.sudoku.adapter.SettingsListAdapter;
import cn.samir.sudoku.core.BackgroundBorderView;
import cn.samir.sudoku.core.InputNumberListener;
import cn.samir.sudoku.core.InputPopupWindow;
import cn.samir.sudoku.core.MoveAction;
import cn.samir.sudoku.core.Number99View;
import cn.samir.sudoku.core.SettingItem;
import cn.samir.sudoku.core.SubItemView;
import cn.samir.sudoku.core.Sudokus;
import cn.samir.sudoku.keys.Conf;
import cn.samir.sudoku.net.NetTask;
import cn.samir.sudoku.util.LogUtils;
import cn.samir.sudoku.util.Utils;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.BitmapHelper;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;

public class GameActivity extends BaseActivity implements OnClickListener,
		InputNumberListener, OnItemClickListener {

	private static final String TAG = "GameActivity";
	View parentView;
	LinearLayout settings_container;
	ArrayList<SettingItem> settingItems = new ArrayList<SettingItem>();
	PopupWindow mSettingsPopupWindow;
	SettingsListAdapter settingsListAdapter;
	ListView popWindowContentView;
	BackgroundBorderView backgroundBorderView;
	InputPopupWindow mInputWindow;
	Sudokus mCurrentGame;
	Number99View backgroundView;
	ImageView iv_pause;
	ImageView iv_share;
	TextView mShowTimeTextView;
	View view;
	Activity mContext = this;
	boolean isPause = false;
	int countSeconds = 0;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:// 计时
				countSeconds++;
				mShowTimeTextView.setText(Utils.formatSeconds(countSeconds));
				handler.sendEmptyMessageDelayed(1, 1000);
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		parentView = View.inflate(this, R.layout.activity_game, null);
		setContentView(parentView);
		initViews();
		handler.sendEmptyMessageDelayed(1, 5000);
	}

	private void initViews() {
		iv_share = getView(R.id.iv_share);
		iv_share.setOnClickListener(this);
		mShowTimeTextView = getView(R.id.tv_time);
		mInputWindow = new InputPopupWindow(this, parentView);
		mInputWindow.setInputNumberListener(this);
		backgroundBorderView = getView(R.id.container);
		backgroundBorderView.setInputPopupWindow(mInputWindow);
		backgroundView = getView(R.id.sudoku_view);
		backgroundBorderView.setNumber99View(backgroundView);
		mInputWindow.setNumber99View(backgroundView);
		/**
		 * intent.putExtra("content", sudokus.content);
		 * intent.putExtra("numberHelp", sudokus.numberHelp);
		 * intent.putExtra("detailExplain", sudokus.detailExplain);
		 * intent.putExtra("level", sudokus.level);
		 */
		// newIntentCome();
		newIntentCome();
		initSettingPopWindow();
	}

	/**
	 * intent.putExtra("content", sudokus.content);
	 * intent.putExtra("numberHelp", sudokus.numberHelp);
	 * intent.putExtra("description", sudokus.description);
	 * 
	 * intent.putExtra("score", sudokus.score); intent.putExtra("sudokuid",
	 * sudokus.sudokuid);
	 */
	public void newIntentCome() {
		Intent intent = getIntent();
		String content = intent.getStringExtra("content");
		int sid = intent.getIntExtra("sid", 0);
		String description = intent.getStringExtra("description");
		// int level = intent.getIntExtra("numberHelp", 1);
		int score = intent.getIntExtra("score", 1);
		int sudokuid = intent.getIntExtra("sudokuid", 0);// ("sudokuid",
															// sudokus.sudokuid);
		mCurrentGame = new Sudokus(sid, sudokuid, content, description, score);
		// mCurrentGame.sudokuid = sudokuid;
		// mCurrentGame.score = score;
		LogUtils.i(TAG, mCurrentGame.toString());
		backgroundView.setGame(mCurrentGame);
		backgroundView.setInputNumberListener(this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		newIntentCome();
		super.onNewIntent(intent);

	}

	@Override
	public void postAction(MoveAction ma) {
		backgroundView.handleAction(ma);

	}

	@Override
	public void readyInput(SubItemView subItemView) {
		Log.i(TAG, subItemView.toString());
		mInputWindow.showInputWindow(subItemView);
	}

	private long ltime = 0l;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_share:
			mSettingsPopupWindow.showAsDropDown(iv_share);
			break;

		default:
			break;
		}
	}

	@Override
	public void onFullCompeleteSuccess(Sudokus sudoku) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(R.drawable.info_warning)
				.setTitle("你这么牛，你朋友知道吗？")
				.setPositiveButton("他们都知道", null)
				.setNegativeButton("去告诉他们",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								ShareSDK.initSDK(mContext);
								OnekeyShare oks = new OnekeyShare();
								// oks.setViewToShare(backgroundView);
								String imagepath = BitmapHelper
										.saveViewToImage(backgroundView);
								LogUtils.i(TAG, imagepath);
								// oks.setTheme(OnekeyShareTheme.SKYBLUE);
								// 关闭sso授权

								oks.disableSSOWhenAuthorize();
								oks.setDialogMode();
								// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
								// oks.setNotification(R.drawable.ic_launcher,
								// getString(R.string.app_name));
								// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
								oks.setTitle("又破解了一题~");
								// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
								oks.setTitleUrl(Conf.apkUrl);
								// text是分享文本，所有平台都需要这个字段
								oks.setText("你也一起来玩 数独 游戏吧~");
								// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
								oks.setImagePath(imagepath);// 确保SDcard下面存在此张图片
								// oks.setImageUrl("http://sudokus.sinaapp.com/logo_96.jpg");
								// url仅在微信（包括好友和朋友圈）中使用
								oks.setUrl(Conf.apkUrl);
								// comment是我对这条分享的评论，仅在人人网和QQ空间使用
								oks.setComment("好玩");
								// site是分享此内容的网站名称，仅在QQ空间使用
								oks.setSite(getString(R.string.app_name));
								// siteUrl是分享此内容的网站地址，仅在QQ空间使用
								oks.setSiteUrl(Conf.apkUrl);
								// 启动分享GUI
								oks.show(mContext);
							}
						});
		builder.show();
		// NetTask netTask = new NetTask(mContext);
		sudoku.time = countSeconds;
		Utils.uploadSudokuSuccessToServer(sudoku, this);

	}

	private void initSettingPopWindow() {

		popWindowContentView = (ListView) View.inflate(this,
				R.layout.pop_listview, null);
		settingsListAdapter = new SettingsListAdapter(this);
		popWindowContentView.setAdapter(settingsListAdapter);
		popWindowContentView.setOnItemClickListener(this);
		mSettingsPopupWindow = new PopupWindow(popWindowContentView);
		mSettingsPopupWindow.setWidth(300);
		mSettingsPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		mSettingsPopupWindow.setBackgroundDrawable(new ColorDrawable());
		mSettingsPopupWindow.setOutsideTouchable(true);
		mSettingsPopupWindow.setTouchable(true);
		mSettingsPopupWindow.setFocusable(true);
		initsettings();
	}

	private void initsettings() {

		settingItems.add(new SettingItem("请好友帮忙", R.drawable.share, 21,
				SettingItem.Item_share));
		settingItems.add(new SettingItem("我完成的", R.drawable.settings, 30,
				SettingItem.Item_Settings));
		Collections.sort(settingItems);
		settingsListAdapter.clear();
		settingsListAdapter.appendToList(settingItems);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		SettingItem item = (SettingItem) settingsListAdapter.getItem(position);
		mSettingsPopupWindow.dismiss();
		switch (item.id) {
		case SettingItem.Item_share:
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("text", "这题不会解，快来帮我下，题目编号是:" + mCurrentGame.sudokuid
					+ "进游戏直接搜编号！");
			String imagepath = BitmapHelper.saveViewToImage(backgroundView);
			params.put("title", "求助");
			params.put("imagePath", imagepath);
			Utils.onekeyshare(mContext, params);
			break;
		case SettingItem.Item_Settings:
			String userid = Utils.getUserId(mContext);
			if (userid != null) {
				Intent settingsIt = new Intent(this, UserHistoryActivity.class);
				startActivity(settingsIt);
			} else {
				showLoginDialog("登录后可以查看所有的历史记录！");
			}
			break;
		default:
			break;
		}

	}

}
